#include "gp2x/gl.h"
#include "SDL/SDL.h"
#include "IL/il.h"

unsigned char render(int frame);

extern SDL_Surface* screen;

int main(int argc, int argv) {
    unsigned char r = 1;
    int frame = 0;
    ILuint ImageName;
    char filename[20];
    unsigned char bytes[320*240*4];

    ilInit();

    ilGenImages(1, &ImageName);
    ilBindImage(ImageName);

    glInit();

    while(r) {
        r = render(frame);

        glFlush();

#ifdef GL2x_REAL
        {
        glFlip();

        glReadPixels(0, 0, 320, 240, GL_RGBA, GL_UNSIGNED_BYTE, &bytes);
        sprintf(filename, "real%i.png", frame);
        }
#else
        {
        int x, y;

        for(x=0; x < 320; x++) {
        for(y=0; y < 240; y++) {
            SDL_GetRGBA(*((int*)(screen->pixels + (y*screen->pitch + x*4))), screen->format, &(bytes[(y*320+x)*4+0]), &(bytes[(y*320+x)*4+1]), &(bytes[(y*320+x)*4+2]), &(bytes[(y*320+x)*4+3]));
        }
        }
        sprintf(filename, "gl2x%i.png", frame);
        }

#endif

        ilTexImage(320, 240, 1, 4, IL_RGBA, IL_UNSIGNED_BYTE, bytes);
        ilSaveImage(filename);

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        frame++;
    }
}
